#include "Lsfile.h"
#include <iostream>
#include <vector>
#include <sstream>
//#include <fstream> iostream to chyba juz zawiera
#include <ctime>
using namespace std;
namespace fs = boost::filesystem;

Lsfile::~Lsfile() {
}
bool Lsfile::ispath() {
	bool what = true;
	if (!fs::is_directory(from)) {
		cout << "Not found: " << from << endl;
		what = false;
	}
	if (!fs::is_directory(to)) {
		cout << "Not found: " << to << endl;
		what = false;
	}
	if(from==to) {
		cout << "Warning from and to PATHs are the same!!";
		what = false;
	}
	return what;
}

void Lsfile::create_ls(fs::path where, const char name[], fs::path main) {
	string ls_name = main.string() + "/" + name;
	if (!ofile.is_open()) {
		ofile.open(ls_name.c_str(), ios::app);
	}
	if (fs::is_directory(where)) {
		fs::directory_iterator end_iter;
		for (fs::directory_iterator dir_iter(where); dir_iter != end_iter;
				++dir_iter) {
			try {
				if (fs::is_directory((*dir_iter).status())) {
					insidepath.push_back((*dir_iter).path().filename().string());
					create_ls((*dir_iter).path(), name, main);
					ofile.open(ls_name.c_str(), ios::app);
				} else {
					string pom = "";
					for (int i = 0; i < (int)insidepath.size(); i++) {
						ofile << '/' << insidepath[i];
						pom += '/' + insidepath[i];
					}
					if((*dir_iter).path().filename().string()!=name){
						time_t sec = fs::last_write_time((*dir_iter).path());
						ofile << '/' <<(*dir_iter).path().filename().string() << "\n" << sec << "\n";
						pom = '/'+(*dir_iter).path().filename().string();
						size.push_back((double)(fs::file_size((*dir_iter).path()))/1048576);
					}
				}
			} catch (const exception & ex) {
				ofile << (*dir_iter).path().filename() << " " << ex.what()
						<< endl;
			}
		}
		if(!insidepath.empty()){
			insidepath.pop_back();
		}
		ofile.close();
	}
}

void Lsfile::createlsvect(){
	string fstr = from.string() + "/" + fromls;
	string tstr = to.string() + "/" + tols;
	iffile.open(fstr.c_str(), ios::out);
	if(iffile.is_open()){
		string data;
		while(iffile.good()){ //is good for i/o operations
			getline(iffile, data);
			fromfile.push_back(data);
		}
	}
	iffile.close();
	iffile.open(tstr.c_str(), ios::out);
	if(iffile.is_open()){
		string data;
		while(iffile.good()){//is good for i/o operations
			getline(iffile, data);
			tofile.push_back(data);
		}
	}
	iffile.close();
}

void Lsfile::clear_file(fs::path where, const char name[]) {
	string clearname = where.string() + "/" + name;
	ofile.open(clearname.c_str(), ios::in);
	if (ofile) {
		ofile.close();
		ofile.open(clearname.c_str(), ios::out | ios::trunc);
	}
	ofile.close();
}

void Lsfile::createAll_ls(const char fstr[], const char tstr[]) {
	fromls = fstr;
	tols = tstr;
	clear_file(to, tstr);
	create_ls(to, tstr, to);
	clear_file(from, fstr);
	create_ls(from, fstr, from);
	createlsvect();
}

